<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的图书馆</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        .fixed-controls {
            position: fixed;
            top: 0;
            width: 100%;
            background-color: white;
            z-index: 10;
            padding: 10px 0;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .table-container {
            margin-top: 100px;
        }

        .pagination {
            position: fixed;
            bottom: 0;
            width: 100%;
            background-color: white;
            z-index: 10;
            padding: 10px 0;
            box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
            text-align: center;
        }

        .book-details {
            padding: 20px;
        }

        .book-details h3 {
            margin-bottom: 20px;
        }

        .book-details p {
            margin-bottom: 10px;
        }

        .book-details ul {
            list-style-type: none;
            padding: 0;
        }

        .book-details ul li {
            margin-bottom: 5px;
        }
        
        .book-cover {
            width: 80px;
            height: 120px;
            object-fit: cover;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            cursor: pointer;
        }
        
        .cover-placeholder {
            width: 80px;
            height: 120px;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #f0f0f0;
            border-radius: 4px;
            color: #909399;
            font-size: 12px;
        }
        
        .detail-cover {
            width: 120px;
            height: 180px;
            object-fit: cover;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
<div id="app">
    <div class="fixed-controls">
        <el-input v-model="searchTitle" placeholder="请输入图书名"
                  style="width: 200px; margin-bottom: 20px;"></el-input>
        <el-input v-model="searchAuthor" placeholder="请输入作者名"
                  style="width: 200px; margin-bottom: 20px;"></el-input>
        <el-input v-model="searchISBN" placeholder="请输入ISBN" style="width: 200px; margin-bottom: 20px;"></el-input>
        <el-input v-model="searchCategory" placeholder="请输入分类"
                  style="width: 200px; margin-bottom: 20px;"></el-input>

        <el-select v-model="sortField" placeholder="选择排序字段" style="width: 200px; margin-bottom: 20px;">
            <el-option label="按图书名排序" value="title"></el-option>
            <el-option label="按作者排序" value="author"></el-option>
            <el-option label="按ISBN排序" value="isbn"></el-option>
            <el-option label="按分类排序" value="category"></el-option>
            <el-option label="按出版日期排序" value="published_date"></el-option>
        </el-select>

        <el-switch v-model="isAsc" active-text="升序" inactive-text="降序" style="margin-bottom: 20px;"></el-switch>

        <el-button type="primary" @click="fetchData">搜索</el-button>
        <el-button type="success" @click="goToBorrowRecords">借阅记录</el-button>
    </div>

    <div class="table-container">
        <el-table :data="books" stripe height="650">
            <el-table-column label="封面" width="100">
                <template slot-scope="scope">
                    <div v-if="scope.row.coverUrl" @click="previewCover(scope.row.coverUrl)">
                        <img :src="scope.row.coverUrl" class="book-cover" alt="封面">
                    </div>
                    <div v-else class="cover-placeholder">
                        暂无封面
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="title" label="图书名"></el-table-column>
            <el-table-column prop="author" label="作者"></el-table-column>
            <el-table-column prop="category" label="分类"></el-table-column>
            <el-table-column prop="isbn" label="ISBN"></el-table-column>
            <el-table-column prop="publishedDate" label="出版日期"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="text" @click="showDetails(scope.row.id)">详情</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <div class="pagination">
        <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="pageSize"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange">
        </el-pagination>
    </div>

    <el-drawer
            title="图书详情"
            :visible.sync="drawerVisible"
            direction="rtl"
            size="300px">
        <div class="book-details" v-if="selectedBook">
            <div v-if="selectedBook.coverUrl" style="text-align: center; margin-bottom: 20px;">
                <img :src="selectedBook.coverUrl" class="detail-cover" alt="封面" @click="previewCover(selectedBook.coverUrl)">
            </div>
            <p><strong>图书名:</strong> {{ selectedBook.title }}</p>
            <p><strong>作者:</strong> {{ selectedBook.author }}</p>
            <p><strong>分类:</strong> {{ selectedBook.category }}</p>
            <p><strong>ISBN:</strong> {{ selectedBook.isbn }}</p>
            <p><strong>出版日期:</strong> {{ selectedBook.publishedDate }}</p>
            <p><strong>复本信息:</strong></p>
            <ul>
                <li v-for="copy in selectedBook.copies" :key="copy.copyId">
                    <strong>复本编号:</strong> {{ copy.copyId }} | <strong>状态:</strong> {{ copy.status }}
                    <el-button v-if="copy.status === '在馆'" type="text" @click="borrowBook(copy.copyId)">借阅
                    </el-button>
                </li>
            </ul>
        </div>
    </el-drawer>
    
    <!-- 封面预览对话框 -->
    <el-dialog title="封面预览" :visible.sync="previewVisible" width="30%">
        <div style="display: flex; flex-direction: column; align-items: center;">
            <img :src="previewCoverUrl" style="max-width: 100%; max-height: 500px; object-fit: contain;">
            <div style="margin-top: 15px;">
                <el-button type="primary" @click="downloadCover">下载封面</el-button>
            </div>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                books: [{}],
                total: 0,
                pageSize: 10,
                currentPage: 1,
                searchTitle: '',
                searchAuthor: '',
                searchISBN: '',
                searchCategory: '',
                sortField: '',
                isAsc: true, // 默认升序
                selectedBook: null, // 用于存储选中的图书详细信息
                drawerVisible: false, // 控制抽屉的显示与隐藏
                previewVisible: false,
                previewCoverUrl: ''
            }
        },
        created() {
            this.fetchData();
        },
        methods: {
            fetchData() {
                const params = {
                    pageNo: this.currentPage,
                    pageSize: this.pageSize,
                };

                if (this.searchTitle) params.title = this.searchTitle;
                if (this.searchAuthor) params.author = this.searchAuthor;
                if (this.searchISBN) params.isbn = this.searchISBN;
                if (this.searchCategory) params.category = this.searchCategory;
                if (this.sortField) params.sortBy = this.sortField;
                params.isAsc = this.isAsc;

                console.log('请求参数:', params);
                axios.get(`/books/page`, {params})
                    .then(response => {
                        console.log('响应数据:', response.data);
                        if (response.data && response.data.data) {
                            // 适应后端返回的数据结构
                            this.books = response.data.data.list || response.data.data.records || [];
                            this.total = response.data.data.total;
                        } else {
                            console.warn("没有返回预期的数据结构");
                        }
                    })
                    .catch(error => {
                        console.error("Error fetching data: ", error);
                    });
            },
            handleSizeChange(size) {
                this.pageSize = size;
                this.fetchData();
            },
            handleCurrentChange(page) {
                this.currentPage = page;
                this.fetchData();
            },
            showDetails(bookId) {
                axios.get(`/books/${bookId}`)
                    .then(response => {
                        if (response.data && response.data.data) {
                            this.selectedBook = response.data.data;
                            this.drawerVisible = true; // 显示抽屉
                        } else {
                            console.warn("没有返回预期的数据结构");
                        }
                    })
                    .catch(error => {
                        console.error("Error fetching book details: ", error);
                    });
            },
            borrowBook(copyId) {
                const userId = sessionStorage.getItem('userId');
                if (!userId) {
                    this.$message.error('用户未登录，无法借阅图书');
                    return;
                }

                // 构造请求对象
                const request = {
                    copyId: copyId,
                    userId: userId
                };

                axios.post('http://localhost:8091/borrowRecords', request, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                    .then(response => {
                    if (response.data && response.data.status === "200") {
                            this.$message.success('借阅成功');
                            // 更新图书状态
                            const copy = this.selectedBook.copies.find(copy => copy.copyId === copyId);
                            if (copy) {
                                copy.status = 'BORROWING'; // 更新复本状态
                            }
                        this.drawerVisible = false;
                        } else {
                            this.$message.error('借阅失败: ' + (response.data.message || '未知错误'));
                        }
                    })
                    .catch(error => {
                        console.error("Error borrowing book: ", error);
                        this.$message.error('借阅请求失败，请稍后重试');
                    });
            },
            goToBorrowRecords() {
                // 从sessionStorage中获取userId
                const userId = sessionStorage.getItem('userId');
                if (!userId) {
                    this.$message.error('用户未登录，无法查看借阅记录');
                    return;
                }
                // 将userId作为参数传递到借阅记录页面
                window.location.href = `/user/borrow/records?userId=${userId}`;
            },
            previewCover(coverUrl) {
                this.previewCoverUrl = coverUrl;
                this.previewVisible = true;
            },
            downloadCover() {
                if (this.previewCoverUrl) {
                    window.open(`/books/download/cover?coverUrl=${encodeURIComponent(this.previewCoverUrl)}`, '_blank');
                }
            }
        }
    });
</script>
</body>
</html>
